#include <ESP8266WiFi.h>

const char *ssid     = "bill";//网络的ssid
const char *password = "12345678";//wifi密码
const char *host = "192.168.5.9";//修改为Server服务端的IP，可以用ipconfig查看下

WiFiClient client;
const int serverPort = 2001;//修改为你建立的Server服务端的端口号

void setup()
{
    Serial.begin(9600);
    Serial.println();
    WiFi.mode(WIFI_STA);//强制设置为sta模式
    WiFi.begin(ssid, password); //连接到wifi
   
    Serial.print("Connecting to router:");
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println();
   
    Serial.print("Connected, IP address: ");
    Serial.println(WiFi.localIP()); //打印分配到的本地ip
}
 
void loop() {
    
    while(!client.connected())  //处理未连接到服务器异常
    {   
        if(!client.connect(host, serverPort))
        {
            delay(500);
            Serial.print(".");
        }
    }
  
    while(client.available())//server数据转发到到串口
    {
        uint8_t dataFromServer = client.read();
        Serial.write(dataFromServer);
    }
  
    if(Serial.available())//串口数据转发到server
    {
        size_t count = Serial.available();
        uint8_t revBuf[count];
        Serial.readBytes(revBuf, count);
        client.write(revBuf, count);
    }

}
